<template>
  <div class="customer-detail-container">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>客户详情</span>
          <div class="header-buttons">
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <!-- 客户基本信息 -->
      <div class="customer-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户名称">{{ customer.name }}</el-descriptions-item>
          <el-descriptions-item label="客户阶段">
            <el-tag :type="getStageType(customer.stage)" size="small" effect="light">
              {{ getStageName(customer.stage) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户来源">{{
            getSourceName(customer.source)
          }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(customer.status)" size="small" effect="light">
              {{ getStatusName(customer.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">{{ customer.contactName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ customer.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="拜访地址" :span="2">{{
            customer.visitAddress
          }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ customer.remark }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 联系人列表 -->
      <div class="contact-list">
        <div class="list-header">
          <h3>联系人列表</h3>
          <el-button type="primary" @click="handleAddContact">新增联系人</el-button>
        </div>

        <el-table
          :data="contacts"
          v-loading="loading"
          stripe
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="name" label="姓名" width="120" align="center" />
          <el-table-column prop="phone" label="电话" width="150" align="center" />
          <el-table-column prop="email" label="邮箱" width="200" align="center" />
          <el-table-column prop="position" label="职位" width="120" align="center" />
          <el-table-column label="关联部门" min-width="200" align="center">
            <template #default="{ row }">
              <el-tag
                v-for="dept in row.departments"
                :key="dept.id"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ dept.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="primary" link @click="handleEditContact(row)">编辑</el-button>
                <el-button type="danger" link @click="handleDeleteContact(row.id)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>

      <!-- 客户日志 -->
      <div class="customer-logs">
        <div class="list-header">
          <h3>客户日志</h3>
        </div>

        <el-timeline v-if="customerLogs.length > 0">
          <el-timeline-item
            v-for="log in customerLogs"
            :key="log.id"
            :timestamp="formatTimestamp(log.operationTime)"
            placement="top"
            :type="getLogType(log.operationType)"
          >
            <el-card>
              <template #header>
                <div class="log-header">
                  <span class="log-type">{{ log.operationTypeLabel }}</span>
                  <span class="log-operator">{{ log.operatorName }}</span>
                </div>
              </template>
              <div class="log-content">
                <p class="log-desc">{{ log.operationDesc }}</p>
                <div v-if="log.statusBefore && log.statusAfter" class="status-change">
                  <span class="status-label">状态变更：</span>
                  <el-tag size="small" type="info">{{ log.statusBefore }}</el-tag>
                  <el-icon><ArrowRight /></el-icon>
                  <el-tag size="small" type="success">{{ log.statusAfter }}</el-tag>
                </div>
                <div v-if="log.details" class="log-details">
                  <span class="details-label">详情：</span>
                  <span>{{ log.details }}</span>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>

        <el-empty v-else description="暂无操作日志" />
      </div>
    </el-card>

    <!-- 联系人表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="关联部门">
          <el-select
            v-model="form.departmentIds"
            multiple
            placeholder="请选择关联部门"
            style="width: 100%"
            @change="(val: number[]) => console.log('部门选择变化:', val)"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import type { Customer, Contact, CustomerLog } from '@/types/customer'
import type { PageResponse } from '@/types/common'
import { getCustomer, getCustomerLogs } from '@/api/customer'
import { getContacts, createContact, updateContact, deleteContact } from '@/api/contact'
import { getAllDepartments } from '@/api/department'
import type { Department } from '@/api/department'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const customer = ref<Customer>({} as Customer)
const contacts = ref<Contact[]>([])
const departments = ref<Department[]>([])
const customerLogs = ref<CustomerLog[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitting = ref(false)

// 表单引用
const formRef = ref()

interface ContactForm extends Partial<Contact> {
  departmentIds: number[]
}

// 联系人表单
const form = reactive<ContactForm>({
  id: undefined,
  name: '',
  phone: '',
  email: '',
  position: '',
  remark: '',
  departmentIds: [],
  customerId: undefined,
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
}

// 客户阶段标签样式
const getStageType = (stage: string) => {
  const types: Record<string, string> = {
    LEAD: 'info',
    QUALIFIED: 'success',
    PROPOSAL: 'warning',
    NEGOTIATION: 'warning',
    CONTRACT: 'success',
    IMPLEMENTATION: 'primary',
    MAINTENANCE: 'success',
    LOST: 'danger',
  }
  return types[stage] || 'info'
}

// 客户阶段显示名称
const getStageName = (stage: string) => {
  const stages = [
    { value: 'LEAD', label: '潜在客户' },
    { value: 'QUALIFIED', label: '已确认需求' },
    { value: 'PROPOSAL', label: '方案报价' },
    { value: 'NEGOTIATION', label: '商务谈判' },
    { value: 'CONTRACT', label: '合同签订' },
    { value: 'IMPLEMENTATION', label: '实施交付' },
    { value: 'MAINTENANCE', label: '售后维护' },
    { value: 'LOST', label: '已流失' },
  ]
  const stageObj = stages.find((s) => s.value === stage)
  return stageObj ? stageObj.label : stage
}

// 客户来源显示名称
const getSourceName = (source: string) => {
  const sources = [
    { value: 'TELEMARKETING', label: '电话营销' },
    { value: 'WEBSITE', label: '官网' },
    { value: 'SOCIAL_MEDIA', label: '社交媒体' },
    { value: 'REFERRAL', label: '客户推荐' },
    { value: 'EXHIBITION', label: '展会' },
    { value: 'SEARCH_ENGINE', label: '搜索引擎' },
    { value: 'EMAIL_MARKETING', label: '邮件营销' },
    { value: 'PARTNER', label: '合作伙伴' },
    { value: 'OTHER', label: '其他' },
  ]
  const sourceObj = sources.find((s) => s.value === source)
  return sourceObj ? sourceObj.label : source
}

// 审核状态标签样式
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    PENDING: 'warning',
    APPROVED: 'success',
    INACTIVE: 'danger',
  }
  return types[status] || 'info'
}

// 审核状态显示名称
const getStatusName = (status: string) => {
  const names: Record<string, string> = {
    PENDING: '待审核',
    APPROVED: '已通过',
    INACTIVE: '已拒绝',
  }
  return names[status] || status
}

// 获取客户详情
const fetchCustomer = async () => {
  try {
    const response = await getCustomer(Number(route.params.id))
    customer.value = response.data
  } catch (error) {
    ElMessage.error('获取客户详情失败')
  }
}

// 获取联系人列表
const fetchContacts = async () => {
  loading.value = true
  try {
    const response = await getContacts({
      page: currentPage.value - 1,
      size: pageSize.value,
      customerId: Number(route.params.id),
    })
    const data = response.data as PageResponse<Contact>
    console.log('获取到的联系人数据:', data.content)
    contacts.value = data.content.map((contact) => ({
      ...contact,
      // 确保departments存在
      departments: contact.departments || [],
    }))
    total.value = data.totalElements
  } catch (error) {
    ElMessage.error('获取联系人列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await getAllDepartments()
    departments.value = response.data
  } catch (error) {
    ElMessage.error('获取部门列表失败')
  }
}

// 获取客户日志
const fetchCustomerLogs = async () => {
  try {
    const response = await getCustomerLogs(Number(route.params.id))
    customerLogs.value = response.data
  } catch (error) {
    ElMessage.error('获取客户日志失败')
  }
}

// 格式化时间戳
const formatTimestamp = (timestamp: number) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 获取日志类型对应的样式
const getLogType = (operationType: string) => {
  const typeMap: Record<string, string> = {
    CREATE: 'success',
    UPDATE: 'primary',
    STATUS_CHANGE: 'warning',
    APPROVE: 'success',
    REJECT: 'danger',
    DEPARTMENT_ADD: 'success',
    DEPARTMENT_REMOVE: 'warning',
    CONTACT_ADD: 'success',
    CONTACT_UPDATE: 'primary',
    CONTACT_DELETE: 'danger',
    DELETE: 'danger'
  }
  return typeMap[operationType] || 'info'
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchContacts()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchContacts()
}

// 新增联系人
const handleAddContact = () => {
  dialogTitle.value = '新增联系人'
  Object.keys(form).forEach((key) => {
            const k = key as keyof ContactForm
        if (k === 'id') {
          form[k] = undefined
        } else if (k === 'departmentIds') {
          form[k] = []
        } else if (k === 'customerId') {
          form[k] = Number(route.params.id)
        } else if (typeof form[k] === 'string') {
          form[k] = '' as any
        }
  })
  form.customerId = Number(route.params.id)
  form.departmentIds = []
  dialogVisible.value = true
}

// 编辑联系人
const handleEditContact = (row: Contact) => {
  dialogTitle.value = '编辑联系人'
  Object.keys(form).forEach((key) => {
    const k = key as keyof Contact
    if (k in row) {
      form[k] = row[k] as any
    }
  })
  console.log('原始联系人数据:', row)
  // 确保从departments正确转换为departmentIds
  form.departmentIds =
    row.departments?.map((dept) => {
      console.log('部门对象:', dept)
      return dept.id
    }) || []
  console.log('转换后的departmentIds:', form.departmentIds)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitting.value = true
      try {
        console.log('提交前表单数据:', JSON.parse(JSON.stringify(form)))
        // 构建提交数据，确保只包含必要字段
        const submitData: Partial<Contact> = {
          id: form.id,
          name: form.name,
          phone: form.phone,
          email: form.email,
          position: form.position,
          remark: form.remark,
          customerId: form.customerId,
          departmentIds: form.departmentIds || []
        }
        console.log('最终提交数据:', submitData)
        console.log('提交数据:', JSON.parse(JSON.stringify(submitData)))

        if (form.id) {
          await updateContact(form.id, submitData)
          ElMessage.success('更新联系人成功')
        } else {
          await createContact(submitData)
          ElMessage.success('创建联系人成功')
        }
        dialogVisible.value = false
        fetchContacts()
      } catch (error) {
        ElMessage.error(form.id ? '更新联系人失败' : '创建联系人失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除联系人
const handleDeleteContact = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该联系人吗？', '提示', {
      type: 'warning',
    })

    await deleteContact(id)
    ElMessage.success('删除联系人成功')
    fetchContacts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除联系人失败')
    }
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化
onMounted(() => {
  fetchCustomer()
  fetchContacts()
  fetchDepartments()
  fetchCustomerLogs()
})
</script>

<style scoped>
.customer-detail-container {
  padding: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.customer-logs {
  margin-top: 30px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-type {
  font-weight: 600;
  color: #409eff;
}

.log-operator {
  font-size: 14px;
  color: #909399;
}

.log-content {
  font-size: 14px;
  line-height: 1.6;
}

.log-desc {
  margin: 0 0 10px 0;
  color: #606266;
}

.status-change {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.status-label,
.details-label {
  font-weight: 500;
  color: #303133;
}

.log-details {
  display: flex;
  gap: 8px;
  color: #606266;
}

.customer-info {
  margin-bottom: 30px;
}

.contact-list {
  margin-top: 30px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin: 0 20px;
}

.el-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  height: 50px;
  padding: 8px 0;
}

.el-table :deep(td) {
  padding: 12px 0;
  height: 50px;
}

.el-table :deep(.cell) {
  line-height: 1.5;
  white-space: nowrap;
  padding: 0 12px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.el-table :deep(.el-button--link) {
  padding: 4px 8px;
  font-size: 14px;
}

.el-table :deep(.el-tag) {
  border-radius: 2px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.el-table :deep(.el-tag--light) {
  border-width: 1px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-button--primary) {
  --el-button-hover-bg-color: #409eff;
  --el-button-hover-border-color: #409eff;
}

:deep(.el-button--danger) {
  --el-button-hover-bg-color: #f56c6c;
  --el-button-hover-border-color: #f56c6c;
}
</style>
